package com.fauks.ssm.springdata.jpa;

import com.fauks.ssm.entity.Customer;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;
import java.util.List;

public class JPQLTest {
    public static void main(String[] args) {
        //testQueryAll();
        //testCount();
        testPage();
    }

    //分页查询
    private static void testPage() {
        EntityManager entityManager = JpaUtils.getEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        String jpql = "from Customer ";
        Query query = entityManager.createQuery(jpql);
        //设置分页条件
        query.setFirstResult(0);
        query.setMaxResults(2);
        List<Customer> resultList = query.getResultList();
        resultList.forEach(System.out::println);
        transaction.commit();
        entityManager.close();
    }

    //查询单条数据
    private static void testCount() {
        EntityManager entityManager = JpaUtils.getEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        String jpql = "select count(custId) from Customer ";
        Query query = entityManager.createQuery(jpql);
        Object singleResult = query.getSingleResult();
        System.out.println(singleResult);
        transaction.commit();
        entityManager.close();
    }

    //查询全部
    private static void testQueryAll() {
        EntityManager entityManager = JpaUtils.getEntityManager();
        EntityTransaction transaction = entityManager.getTransaction();
        transaction.begin();
        //条件、排序查询
        String jpql = "from Customer where custName like ? order by custId desc ";
        //创建query查询对象，是jpql对象
        Query query = entityManager.createQuery(jpql);
        query.setParameter(1, "Fauks%");
        //查询集合
        List<Customer> resultList = query.getResultList();
        resultList.forEach(System.out::println);
        transaction.commit();
        entityManager.close();
    }
}
